package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.SportPlanItemEntity;

public class SportPlanItemDAO {
	public int insert(Connection conn, SportPlanItemEntity entity) throws SQLException {
		int id = -1;
		PreparedStatement ps = conn.prepareStatement(
				"insert into sport_plan_item(sport_plan_id,way,per,time,times) values(?,?,?,?,?)",
				Statement.RETURN_GENERATED_KEYS);
		ps.setInt(1, entity.getSport_id());
		ps.setString(2, entity.getWay());
		ps.setString(3, entity.getPer());
		ps.setInt(4, entity.getTime());
		ps.setInt(5, entity.getTimes());
		if (ps.executeUpdate() > 0) {
			ResultSet rSet = ps.getGeneratedKeys();
			if (rSet.next()) {
				id = rSet.getInt(1);
			}
		}
		return id;

	}

	public boolean update(Connection conn, SportPlanItemEntity entity) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn
				.prepareStatement("update sport_plan_item set sport_plan_id=?,way=?,per=?,time=?,times=? where id=?");
		ps.setInt(1, entity.getSport_id());
		ps.setString(2, entity.getWay());
		ps.setString(3, entity.getPer());
		ps.setInt(4, entity.getTime());
		ps.setInt(5, entity.getTimes());
		ps.setInt(6, entity.getId());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;

	}

	public SportPlanItemEntity findById(Connection conn, int id) throws SQLException {
		SportPlanItemEntity entity = null;
		PreparedStatement ps = conn.prepareStatement("select * from sport_plan_item where id =? ");
		ps.setInt(1, id);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			entity = fill(rs);
		}
		return entity;
	}

	private SportPlanItemEntity fill(ResultSet rs) throws SQLException {
		SportPlanItemEntity entity = new SportPlanItemEntity();
		entity.setId(rs.getInt("id"));
		entity.setPer(rs.getString("per"));
		entity.setTime(rs.getInt("time"));
		entity.setWay(rs.getString("way"));
		entity.setSport_id(rs.getInt("sport_plan_id"));
		entity.setTimes(rs.getInt("times"));
		return entity;
	}

	public void delete(Connection conn, int sport_plan_id) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("delete from sport_plan_item where sport_plan_id=?");
		ps.setInt(1, sport_plan_id);
		ps.executeUpdate();
	}

	
	public List<SportPlanItemEntity> listByPlanId(Connection conn, int id) throws SQLException {
		List<SportPlanItemEntity> list = new LinkedList<>();
		PreparedStatement ps = conn.prepareStatement("select * from sport_plan_item where sport_plan_id =? ");
		ps.setInt(1, id);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			SportPlanItemEntity entity = fill(rs);
			list.add(entity);
		}
		return list;
	}
}
